package com.example.api.service.impl;

import com.example.api.model.entity.Commodity;
import com.example.api.model.entity.Inventory;
import com.example.api.model.entity.Sale;
import com.example.api.model.entity.Warehouse;
import com.example.api.repository.CommodityRepository;
import com.example.api.repository.InventoryRepository;
import com.example.api.repository.SaleRepository;
import com.example.api.repository.WareHouseRepository;
import com.example.api.service.SaleService;
import com.example.api.utils.DataTimeUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Service
public class SaleServiceImpl implements SaleService {

    @Resource
    private SaleRepository saleRepository;

    @Resource
    private CommodityRepository commodityRepository;

    @Resource
    private WareHouseRepository wareHouseRepository;

    @Resource
    private InventoryRepository inventoryRepository;

    @Override
    public Sale save(Sale sale) throws Exception {
        sale.setCreateAt(DataTimeUtil.getNowTimeString());
        boolean is = true;
        // 减商品库存量
        Commodity commodity = commodityRepository.findById(sale.getCommodity()).orElse(null);
        if (commodity == null) {
            is = false;
            commodity = commodityRepository.findByName(sale.getCommodity());
            if (commodity == null){
                throw new Exception("参数异常，请重新提交!");
            }
        };
        if (is){
            if (commodity.getCount() < Integer.parseInt(sale.getCount())) throw new Exception("商品数量不足");
            commodity.setCount(commodity.getCount()-Integer.parseInt(sale.getCount()));

            // 减仓库
            Integer count = Integer.parseInt(sale.getCount());
            for (Inventory inventory : inventoryRepository.findAll()) {
                if (Objects.equals(inventory.getCid(), commodity.getId())){
                    if (inventory.getCount() >= count){
                        inventory.setCount(inventory.getCount() - count);
                        inventoryRepository.save(inventory);
                        break;
                    } else {
                        count = count - inventory.getCount();
                        inventory.setCount(0);
                        inventoryRepository.save(inventory);
                    }
                }
            }

        }
        commodityRepository.save(commodity);

        sale.setCommodity(commodity.getName());
        return saleRepository.save(sale);
    }

    @Override
    public List<Sale> findAll() {
        return saleRepository.findAll();
    }

    @Override
    public List<Sale> searchByCompany(String name) {
        return saleRepository.findAllByCompanyLike(name);
    }

}
